package com.example.sea.back.web.user;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.example.sea.back.common.context.AdminContext;
import com.example.sea.back.common.context.SessionKeyContext;
import com.example.sea.core.common.utils.Md5Util;
import com.example.sea.core.data.user.AuthUserEunm;
import com.example.sea.core.data.user.entity.AuthRole;
import com.example.sea.core.data.user.entity.AuthUser;
import com.example.sea.core.data.user.model.AuthUserModel;
import com.example.sea.core.data.user.service.AuthRoleService;
import com.example.sea.core.data.user.service.AuthUserService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 *
 * @author zengyz
 * @date 2018/7/9 下午 3:09
 */
@Controller
@RequestMapping("/user/admin")
public class UserController {

    private Logger log=LoggerFactory.getLogger(UserController.class);

    @Autowired
    private AuthUserService authUserService;

    @Autowired
    private AuthRoleService authRoleService;


    /**
     * List页面
     * @param request
     * @param pageNum
     * @param pageSize
     * @param state
     * @param account
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/index")
    public String indexHtml(HttpServletRequest request, Integer pageNum, Integer pageSize, Integer state, String account){
        Map params=new HashMap();
        params.put("pageNum",pageNum==null?1:pageNum);
        params.put("pageSize",pageSize==null?10:pageSize);
        params.put("state",state);
        params.put("account",StringUtils.isEmpty(account)?null:"%"+account+"%");
        PageInfo<AuthUserModel> pageInfo = authUserService.findPageByParams(params);
        request.setAttribute("pageInfo",pageInfo);
        /**
         * 回显数据
         */
        request.setAttribute("state",state);
        request.setAttribute("account",account);
        return "user/admin/index";
    }

    /**
     * 添加页面
     * @param request
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/add")
    public String addHtml(HttpServletRequest request){
        AuthUser authUser = (AuthUser) SecurityUtils.getSubject().getSession().getAttribute(SessionKeyContext.SESSION_LOGIN_ADMIN_USER);
        List<AuthRole> authRoleList = authRoleService.findRoleByStateIsOkToAll();
        request.setAttribute("authRoles",authRoleList);
        return "user/admin/add";
    }

    /**
     * 添加
     * @param authUser
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/add")
    public Map addSubmit(AuthUser authUser){
        Map resultMap=new HashMap();
        int add = authUserService.add(authUser);
        if (add==1){
            resultMap.put("code",200);
        }else{
            resultMap.put("code",500);
        }
        return resultMap;
    }

    /**
     * 删除
     * @param request
     * @param chkids
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/delete")
    public Map deleteSubmit(HttpServletRequest request,String chkids){
        Map resultMap=new HashMap();
        String[] ids = chkids.split(",");
        int delete = authUserService.delete(ids);
        if (delete!=ids.length){
            resultMap.put("code",500);
        }else{
            resultMap.put("code",200);
        }
        return resultMap;
    }

    /**
     * 修改状态
     * @param request
     * @param id
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/state")
    public Map stateSubmit(HttpServletRequest request,String id){
        Map resultMap=new HashMap();
        AuthUser authUser = authUserService.findById(id);
        if (authUser.getState().equals(AuthUserEunm.STATE_NO.getValue())){
            authUser.setState(AuthUserEunm.STATE_OK.getValue());
        }else if(authUser.getState().equals(AuthUserEunm.STATE_OK.getValue())){
            authUser.setState(AuthUserEunm.STATE_NO.getValue());
        }
        int update = authUserService.update(authUser);
        if (update==0){
            resultMap.put("code",500);
        }else{
            resultMap.put("code",200);
        }
        return resultMap;
    }

    /**
     * 修改页面
     * @param request
     * @param id
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/update")
    public String updateHtml(HttpServletRequest request,String id){
        AuthUser authUser = authUserService.findById(id);
        request.setAttribute("authUser",authUser);

        List<AuthRole> authRoleList = authRoleService.findRoleByStateIsOkToAll();
        request.setAttribute("authRoles",authRoleList);
        return "user/admin/edit";
    }

    /**
     * 修改
     * @param authUser
     * @return
     */
    @ResponseBody
    @PostMapping("/update")
    public Map updateSubmit(AuthUser authUser){
        Map resultMap=new HashMap();
        AuthUser oldEntity = authUserService.findById(authUser.getId());

        if (!StringUtils.isEmpty(authUser.getPassword())){
            oldEntity.setPassword(Md5Util.getMd5(authUser.getPassword()));
        }

        oldEntity.setAccount(authUser.getAccount());
        oldEntity.setState(authUser.getState());
        oldEntity.setRoleId(authUser.getRoleId());
        int add = authUserService.update(oldEntity);
        if (add==1){
            resultMap.put("code",200);
        }else{
            resultMap.put("code",500);
        }
        return resultMap;
    }

    private boolean isAdminAccount(AuthUser authUser, Map resultMap, AuthUser oldEntity) {
        if (authUser.getId().equals(AdminContext.ADMIN_ID)){
            int count=0;
            if (!authUser.getAccount().equals(oldEntity.getAccount())){
                count+=1;
            }
            if (authUser.getState()!=oldEntity.getState()){
                count+=1;
            }
            if (!authUser.getRoleId().equals(oldEntity.getRoleId())){
                count+=1;
            }
            if (count!=0){
                resultMap.put("code",600);
                return true;
            }
        }
        return false;
    }


}
